<%@ page language="java" contentType="text/json; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" import="java.io.*, java.util.*, java.net.*, org.OpenGeoPortal.Download.*, org.springframework.context.support.*, org.springframework.beans.factory.* " %>

<%
	 /*
	 * This jsp should receive a POST request with an object containing 
	 * all the info needed for each layer to be downloaded.  The jsp calls a class 
	 * that will create a download directory if it doesn't exist. Then the jsp will iterate over each layer, 
	 * calling a class that will download each into the directory, using the 
	 * appropriate method.  Once this is complete the jsp will call another class to 
	 * zip the directory contents, delete the original files, and the jsp will return a link to the
	 * zip-file... this allows us to leverage AJAX methods.  There may also be 
	 * an option to email a link to the zip-file to the user.
	 * @author Chris Barnett
	 */

	if (request.getMethod() != "POST"){
		//only allow POST requests
		response.setStatus(403);
	}

	  //do data validation here
	String layerIds = request.getParameter("layers");
	String emailAddress = request.getParameter("email");
	String[] bbox = request.getParameterValues("bbox");
	String[] layers = layerIds.split("&");
	Map<String,String> layerMap = new HashMap<String,String>();
	for (int i = 0; i < layers.length; i++){
		String[] layerInfo = layers[i].split("=");
		layerMap.put(layerInfo[0], layerInfo[1]);
	}

	//String contextPath = request.getContextPath();
	Boolean authenticated = false;

	try {
		String userName = session.getAttribute("username").toString();
		if (!userName.trim().isEmpty()){
			authenticated = true;
		}
	} catch (NullPointerException e){
		//
	}

	//System.out.println(System.getProperty("user.dir"));

	/*WebApplicationContext applicationContext = new XmlWebApplicationContext();
	Boolean test = applicationContext.hasBeanFactory();
	System.out.println(test);
	applicationContext.refreshBeanFactory();
	BeanFactory injector = xmlWebApplicationContext.getBeanFactory();*/
	String contextRelativePath = "";
	contextRelativePath += "../webapps/ROOT/";    
	String contextConfigPath = contextRelativePath + "WEB-INF/download.xml";    
	BeanFactory injector = new FileSystemXmlApplicationContext(contextConfigPath);
	DownloadHandler downloadHandler = (DownloadHandler) injector.getBean("downloadPackager");
	downloadHandler.setContextConfigPath(contextConfigPath);
	downloadHandler.setLocallyAuthenticated(authenticated);
	downloadHandler.setReplyEmail(emailAddress);
	downloadHandler.requestLayers(layerMap, bbox);
	
	//return a link to the zip file, or info to create link  
	response.getWriter().write(downloadHandler.getJsonResponse());
	
%>
